package com.myk.game.heroscuffle.ui;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.myk.game.heroscuffle.R;
import com.myk.game.heroscuffle.utils.FastUtil;

public class GameCtrlLayout extends FrameLayout {

    private Button[] buttons;
    private int curIndex;

    //初始化
    private void init(Context context) {
        inflate(context, R.layout.layout_game_ctrl, this);
        curIndex = 0;
        buttons = new Button[getChildCount()];
        for (int i = 0; i < getChildCount(); i++) {
            buttons[i] = (Button) getChildAt(i);
        }
    }

    /**
     * 添加一个操作按钮
     */
    public void addButton(String title, Runnable action) {
        Button button = buttons[curIndex];
        button.setVisibility(VISIBLE);
        button.setText(title);
        button.setTextColor(Color.BLACK);
        button.setOnClickListener(v -> {
            if (FastUtil.isNotFast("CtrlClick", 300)) {
                action.run();
            }
        });
        curIndex++;
    }

    /**
     * 添加一个操作按钮
     */
    public void addButton(String title, boolean usable, Runnable action) {
        Button button = buttons[curIndex];
        button.setVisibility(VISIBLE);
        button.setText(title);
        if (usable) {
            button.setTextColor(Color.BLACK);
            button.setOnClickListener(v -> {
                if (FastUtil.isNotFast("CtrlClick", 500)) {
                    action.run();
                }
            });
        }
        else {
            button.setTextColor(Color.GRAY);
            button.setOnClickListener(null);
        }
        curIndex++;
    }

    /**
     * 清空所有操作按钮
     */
    public void resetAllButtons() {
        curIndex = 0;
        for (Button button : buttons) {
            button.setText("");
            button.setTextColor(Color.BLACK);
            button.setVisibility(GONE);
            button.setOnClickListener(null);
        }
    }

    public GameCtrlLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GameCtrlLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

}
